/**
 * User: alesj
 * Date: 2005.2.23
 * Time: 12:54:49
 * 
 * (C) Genera Lynx d.o.o.
 */

package com.generalynx.common.web.tags;

import com.generalynx.common.constants.WebConst;
import org.springframework.web.util.TagUtils;

import javax.servlet.jsp.JspException;
import java.util.Random;

public class TreeTag extends CommonWriteTag implements IRootable {

    //consts
    public static final String TREE_ID = "treeId";
    public static final String PLUS = "plus";
    public static final String MINUS = "minus";

    //ui
    private String plus = WebConst.FRONTCONTROLLER + "/images/plus.gif";
    private String minus = WebConst.FRONTCONTROLLER + "/images/minus.gif";
    private String css = "treedefault";

    private String openNodes;
    private String formObjectName;

    //form object must be in request scope
    private Object root;

    public Object getRoot() {
        return root;
    }

    public int doStartTag() throws JspException {
        root = pageContext.getAttribute(formObjectName, TagUtils.getScope(TagUtils.SCOPE_REQUEST));

        int treeId = (Math.abs(new Random().nextInt()));
        pageContext.setAttribute(TREE_ID, new Integer(treeId));
        pageContext.setAttribute(PLUS, plus);
        pageContext.setAttribute(MINUS, minus);
        //for usage with MaskGenerator
        write("<input type=\"hidden\" name=\"" + TREE_ID + "\" value=\"" + treeId + "\">\n\n");
        //render tree
        write("<div class=\"" + css + "\">");

        return EVAL_BODY_INCLUDE;
    }

    public int doEndTag() throws JspException {

        write("</div>\n");
        writeFinalJavascript();

        return EVAL_PAGE;
    }

    private void writeFinalJavascript() throws JspException {
        if (openNodes != null) {
            String[] nodeNames = openNodes.split(", *");
            StringBuffer str = new StringBuffer("<script type='text/javascript'>\n");
            for (int i = 0; i < nodeNames.length; i++) {
                String nodeName = nodeNames[i];
                str.append("  openCheckedNodes(" + pageContext.getAttribute(TREE_ID) + ", '" + nodeName + "', '" + plus + "', '" + minus + "');\n");
            }
            str.append("</script>\n");
            write(str.toString());
        }
    }

    // --------------------------------------------------------------------- //

    public void setPlus(String plus) {
        this.plus = plus;
    }

    public void setMinus(String minus) {
        this.minus = minus;
    }

    public void setCss(String css) {
        this.css = css;
    }

    public void setOpenNodes(String openNodes) {
        this.openNodes = openNodes;
    }

    public void setFormObjectName(String formObjectName) {
        this.formObjectName = formObjectName;
    }
}
